<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
//use App\Http\Models\CarModel;
use Illuminate\Http\Request;
use App\Model\CarFactory;

class FactoryController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //

    /**
     * 获取brands
     */
    public function getList( Request $request ){

        $res = [];
        $get = $request->all();
        $page = isset( $get['page'] )? intval($get['page']) : 1;
        $number = isset( $get['number'] )? intval($get['number']) : 20;
        $where = [];
        if( !empty( $get['brand_name'] ) ){
            $where[] =[ 'car_brand.name', 'like', '%' . $get['brand_name'] .'%'];
        }
        if( !empty( $get['brand_id'] ) ){
            $where[] =[ 'car_brand.id', '=',  $get['brand_id'] ];
        }

        if( !empty( $get['name'] ) ){
            $where[] =[ 'car_factory.name', 'like', '%' . $get['name'] .'%'];
        }
        $list = CarFactory::where( $where )
            ->leftJoin('car_brand','car_brand.id', '=', 'car_factory.brand_id')
            ->forPage($page, $number)
            ->select('car_brand.id as brand_id'
                , 'car_brand.name as brand_name'
                , 'car_factory.id'
                , 'car_factory.name'
                )
        ->get();

        $count = CarFactory::where( $where )
            ->leftJoin('car_brand','car_brand.id', '=', 'car_factory.brand_id')
            ->count();

        $res = [
            'status'=>0,
            'total'=> $count,
            'page_total'=> ceil( $count / $number),
            'list'=> $list
        ];
        echo json_encode( $res );
    }

    /**
     * 获取brand 根据brand_id
     */
    public function single( $id ){

        $factory = CarFactory::where('car_factory.id',$id)
            ->leftJoin('car_brand','car_brand.id', '=', 'car_factory.brand_id')
            ->select(
                'car_factory.id',
                'car_factory.name',
                'car_brand.id as brand_id',
                'car_brand.name as brand_name'
            )
            ->get();
        $single = !empty( $factory ) ? $factory[0] : '';
        echo json_encode( $single );
    }

    /**
     * 获取brand 根据brand_id
     */
    public function factory_edit( Request $request, $factory_id ){

        $post = $request->all();
        $params = $post;
        if( !empty($factory_id) ){
            $res = CarFactory::edit($factory_id, $params);
        }else{
            $car_factory = new CarFactory();
            $car_factory->brand_id = $params['brand_id'];
            $car_factory->name = $params['name'];
            $res = $car_factory->save();
        }

        echo json_encode( $res );
    }

}
